// 高阶函数-函数作为参数

function forEach(array, fn, context) {
  if (typeof fn !== 'function') {
    throw TypeError(`Uncaught TypeError: ${fn} is not a function`);
  }
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    fn.call(context, element, index, array);
  }
}

// 测试
// let arr = [1, 3, 4, 7, 8];
// let obj = { a: 1 };
// forEach(
//   arr,
//   function (item, index, array) {
//     console.log(item, index, array, this);
//   },
//   obj,
// );

// filter
function filter(array, fn, context) {
  if (typeof fn !== 'function') {
    throw TypeError(`Uncaught TypeError: ${fn} is not a function`);
  }
  let results = [];
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    if (fn.call(context, element, index, array)) {
      results.push(element);
    }
  }
  return results;
}

// 测试
let arr = [1, 3, 4, 7, 8];
let obj = { a: 1 };
let r = filter(
  arr,
  function (item, index, array) {
    console.log(item, index, array, this);
    return item % 2 === 0;
  },
  obj,
);

console.log(r);
